package com.eregg.learn.netty.protocol.client;

import com.eregg.learn.netty.protocol.client.handler.LoginResponseHandler;
import com.eregg.learn.netty.protocol.client.handler.MessageResponseHandler;
import com.eregg.learn.netty.protocol.codec.PacketDecoder;
import com.eregg.learn.netty.protocol.codec.PacketEncoder;
import com.eregg.learn.netty.protocol.codec.Spliter;
import com.eregg.learn.netty.protocol.protocol.request.LoginRequestPacket;
import com.eregg.learn.netty.protocol.protocol.request.MessageRequestPacket;
import com.eregg.learn.netty.protocol.protocol.response.LoginResponsePacket;
import com.eregg.learn.netty.protocol.util.SessionUtil;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.util.concurrent.Future;
import io.netty.util.concurrent.GenericFutureListener;

import java.util.Date;
import java.util.Scanner;
import java.util.concurrent.TimeUnit;

public class NettyClient {

    private static final String HOST = "127.0.0.1";
    private static final int PORT = 8000;
    private static final int MAX_RETRY = 5;

    public static void main(String[] args) {
        Bootstrap bootstrap = new Bootstrap();
        NioEventLoopGroup workerGroup = new NioEventLoopGroup();

        bootstrap
                .group(workerGroup)
                .channel(NioSocketChannel.class)
                .handler(new ChannelInitializer<NioSocketChannel>() {
                    @Override
                    protected void initChannel(NioSocketChannel nioSocketChannel) throws Exception {
                        nioSocketChannel.pipeline().addLast(new Spliter());
                        nioSocketChannel.pipeline().addLast(new PacketDecoder());
                        nioSocketChannel.pipeline().addLast(new LoginResponseHandler());
                        nioSocketChannel.pipeline().addLast(new MessageResponseHandler());
                        nioSocketChannel.pipeline().addLast(new PacketEncoder());
                    }
                });

        connect(bootstrap, HOST, PORT, 5);
    }

    public static void connect(Bootstrap bootstrap, String host, int port, int retry){
        bootstrap.connect(host, port).addListener(new GenericFutureListener<Future<? super Void>>() {
            @Override
            public void operationComplete(Future<? super Void> future) throws Exception {
                if (future.isSuccess()) {
                    System.out.println(String.format("[%s]连接成功", new Date()));
                    Channel channel = ((ChannelFuture) future).channel();
                    startConsoleThread(channel);
                } else if(retry > 0){
                    //第几次尝试
                    int order = MAX_RETRY - retry + 1;
                    int delay = 1 << order;
                    System.out.println(String.format("[%s]连接服务器失败, [%s]秒后执行第[%s]次尝试", new Date(), delay, order));
                    bootstrap.config().group().schedule(()->{
                        connect(bootstrap, host, port, retry -1);
                    }, delay, TimeUnit.SECONDS);
                }
            }
        });
    }

    private static void startConsoleThread(Channel channel) {
        Scanner scanner = new Scanner(System.in);

        new Thread(()->{
            while (!Thread.interrupted()){
                if(!SessionUtil.hasLogin(channel)){
                    System.out.println("请输用户名:");

                    String username = scanner.nextLine();

                    LoginRequestPacket loginRequestPacket = new LoginRequestPacket();
                    loginRequestPacket.setUsername(username);
                    loginRequestPacket.setPassword(username);

                    channel.writeAndFlush(loginRequestPacket);
                    waitForLoginResponse();
                }else{
                    String toUserId = scanner.next();
                    String message = scanner.next();
                    MessageRequestPacket messageRequestPacket = new MessageRequestPacket();
                    messageRequestPacket.setToUserId(toUserId);
                    messageRequestPacket.setMessage(message);
                    channel.writeAndFlush(messageRequestPacket);
                }
            }
        }).start();
    }

    private static void waitForLoginResponse() {
        try {
            Thread.sleep(1000);
        } catch (InterruptedException ignored) {
        }
    }

}
